package com.wangl.spring.listener;

import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;
import com.wangl.spring.localstorage.LocalStorage;
import com.wangl.spring.service.SuggestionService;
import com.wangl.spring.service.chain.SuggestionTreeBuilderChain;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;

import static com.wangl.spring.utils.PsiCustomUtil.findFile;
import static com.wangl.spring.utils.PsiCustomUtil.findModule;

/**
 * @ClassName SpringJavaFileEditorManagerListener
 * @Description TODO
 * @Author wangl
 * @Date 2023/4/25 14:02
 */
public class SpringJavaFileEditorManagerListener implements FileEditorManagerListener {
    @Override
    public void selectionChanged(@NotNull FileEditorManagerEvent event) {
        if (event.getOldEditor() == null){
            return;
        }
        if (LocalStorage.currentProject == null || !LocalStorage.currentProject.isOpen()){
            return;
        }
        VirtualFile oldFile = event.getOldFile();
        if (!oldFile.isValid() || !oldFile.isInLocalFileSystem()){
            return;
        }
        DumbService.getInstance(LocalStorage.currentProject).runWhenSmart(() -> {
            PsiFile psiFile = findFile(LocalStorage.currentProject, oldFile);
            if (psiFile == null){
                return;
            }
            Module module = findModule(psiFile);
            if (module == null) {
                return;
            }
            SuggestionService service = module.getService(SuggestionService.class);
            if (!service.isCanSuggest()){
                return;
            }
            if (psiFile instanceof PsiJavaFile && Objects.equals(psiFile.getVirtualFile().getExtension(), JavaFileType.DEFAULT_EXTENSION)){
                service.getSuggestionNodeTree().remove(psiFile);
                PsiClass[] psiClasses = ((PsiJavaFile) psiFile).getClasses();
                for (PsiClass psiClass : psiClasses) {
                    SuggestionTreeBuilderChain.getInstance().build(service.getSuggestionNodeTree(), psiClass);
                }
            }
        });
    }
}
